const config = require("./config.json");
const utils = require("./utils.js");
const fs = require("node:fs");

(async () => {
  const res = await fetch(config.FOLLOWING_API, {
    headers: {
      Cookie: config.cookie
    }
  }).then(r => r.json());

  if (res.code !== 0) {
    throw new Error(res.message);
  }

  const ups = res.data.list.map(u => ({
    name: u.uname,
    id: u.mid,
  }));

  console.log("关注的up数据获取成功");

  const browser = await require("puppeteer").launch();
  const durationUps = []

  for (let i = 0; i < ups.length; i++) {
    const up = ups[i];

    const page = await browser.newPage();
    await page.goto(`https://space.bilibili.com/${up.id}/video`);
    await page.waitForNetworkIdle()

    const pageRes = await page.evaluate(() => {
      const videoEl = document.querySelector('#submit-video-list > ul.clearfix.cube-list > li.small-item.fakeDanmu-item');
      if (!videoEl) return {
        name: "",
        time: "2000-10-10"
      };
      return {
        name: videoEl.querySelector('.title').innerText,
        time: videoEl.querySelector('.time').innerText,
        duration: videoEl.querySelector('.length').innerText
      }
    });
    
    if (pageRes.duration) {
      durationUps.push({
        name: pageRes.name,
        duration: pageRes.duration
      })
    }

    up.video = {
      name: pageRes.name,
      ...utils.getTimeStamp(pageRes.time)
    }
    await page.close();
    console.log(`爬取「${up.name}」完成  ${i + 1}/${ups.length}`);
    console.log('~~~~~~~~~~ 发布时间 ~~~~~~~~~~')
    console.log(up, pageRes.time, pageRes.duration)
    
    // await utils.sleep()
  }

  await browser.close();
  console.log("所有数据爬完");

  ups.sort((a, b) => a.video.timestamp - b.video.timestamp);
  
  fs.writeFileSync("结果.txt", ups.reduce((total, cur) => {
    total += `  up：${cur.name}\n视频：${cur.video.name}\n时间：${cur.video.timeText}\n相差：${cur.video.diff}天\n\n`
    return total;
  }, ""), "utf-8");
  
  if (durationUps.length) {
    const longVideoUps = [] // 第一个视频时间超过 15 分钟的 up 主
    durationUps.forEach(u => {
      const d = u.duration.padStart(8, '00:')
      const [h,m,s] = d.split(':')
      const ms=h*3600+m*60+s*1
      if(ms>15*60){
        longVideoUps.push(u)
      }
    })
    if(longVideoUps.length){
      const c=longVideoUps.reduce((a,b)=>
          a+`${b.name}-----${b.duration}
`
      ,"");
      fs.writeFileSync("长视频的up主们.txt",c,"utf-8");
    }
  }

  console.log("写入文件完成");
})();
